// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.

const serialPort = require('serialport');
const createTable = require('data-table');

serialPort.list((err, ports) => {
  console.log('ports', ports);
  if (err) {
    document.getElementById('error').textContent = err.message
    return
  } else {
    document.getElementById('error').textContent = ''
  }

  if (ports.length === 0) {
    document.getElementById('error').textContent = 'No ports discovered'
    return;
  }

  const port = new serialPort('COM2');
  const headers = Object.keys(ports[0])
  const table = createTable(headers)
  tableHTML = ''
  table.on('data', data => tableHTML += data)
  table.on('end', () => document.getElementById('ports').innerHTML = tableHTML)
  ports.forEach(port => table.write(port))
  table.end();

  port.on('open', () => {
    console.log('串口打开');
  });

  port.on('data', function (data) {
    console.log('Data:', data);
  });

  port.on('readable', function () {
    console.log('Data:', port.read());
  });
})
